﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace NewAI.Tools
{
    public sealed class IniReadWrite
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        private IniReadWrite() { }


        /// <summary>
        /// 写配置项
        /// </summary>
        /// <param name="filePath">文件名（全路径）</param>
        /// <param name="section">段落名</param>
        /// <param name="key">键名</param>
        /// <param name="val">值</param>
        /// <returns></returns>
        public static bool Write(string filePath, string section, string key, string val)
        {
            try
            {
                WritePrivateProfileString(section, key, val, filePath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 读配置项
        /// </summary>
        /// <param name="filePath">文件名（全路径）</param>
        /// <param name="section">段落名</param>
        /// <param name="key">键名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static string Read(string filePath, string section, string key, string defaultValue)
        {
            StringBuilder retVal = new StringBuilder();
            GetPrivateProfileString(section, key, defaultValue, retVal, 500, filePath);
            return retVal.ToString();
        }
    }
}
